package main

import (
	"net/http"

	"gitee.com/wangxuanbo/soso/admin"
	"gitee.com/wangxuanbo/soso/chat"
	log "github.com/cihub/seelog"
	"github.com/julienschmidt/httprouter"
)

func main() {
	defer log.Flush()
	createLogger()

	// http router
	router := httprouter.New()

	// WebSocket server
	chat.ChatServer = chat.NewServer("/soso")
	go chat.ChatServer.Listen(router)

	// Rest API
	router.POST("/broadcast", admin.Broadcast)

	// Index Page
	router.GET("/", indexPage)

	// Static files
	router.ServeFiles("/web/*filepath", http.Dir("pages"))

	log.Info("Listen on 1234. Go to http://127.0.0.1:1234")
	if err := http.ListenAndServe(":1234", router); err != nil {
		log.Error("Listen and serve error. ", err)
	}
}

func createLogger() {
	logger, err := log.LoggerFromConfigAsFile("conf/seelog.xml")
	if err != nil {
		log.Error("parse seelog file error. ", err)
		return
	}
	log.ReplaceLogger(logger)
}

func indexPage(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	http.Redirect(w, r, "/web", 302)
}
